const setWatermark = (str: string) => {
  const id = '1.234567890.123456'
  if (document.getElementById(id) != null) {
    document.body.removeChild(document.getElementById(id) as HTMLElement)
  }
  //创建水印
  const can = document.createElement('canvas')
  //设置can的宽高
  can.width = 200
  can.height = 150
  const cvs = <CanvasRenderingContext2D>can.getContext('2d')
  cvs.rotate((-20 * Math.PI) / 180)
  cvs.font = '12px Microsoft JhengHei'
  cvs.fillStyle = 'rgba(200, 200, 200, 0.3)'
  cvs.textBaseline = 'middle'
  cvs.fillText(str, can.width / 10, can.height / 2)
  const div = document.createElement('div')
  div.id = id
  div.style.pointerEvents = 'none'
  div.style.position = 'fixed'
  div.style.top = '0px'
  div.style.left = '0px'
  div.style.zIndex = '100000'
  div.style.width = `${document.documentElement.clientWidth}px` // 窗口宽度
  div.style.height = `${document.documentElement.clientHeight}px` // 窗口高度
  div.style.background = `url(${can.toDataURL('image/png')}) left top repeat`
  document.body.appendChild(div)
  return id
}

/** 定义一个水印对象 */
const watermark = {
  /** 设置水印 */
  set: (str: string) => {
    // 调用setWatermark函数设置水印，返回水印id
    let id = setWatermark(str)
    // 如果document中不存在该id的水印，则再次调用setWatermark函数设置水印
    if (document.getElementById(id) == null) {
      id = setWatermark(str)
    }
  },
  /** 删除水印 */
  del: () => {
    // 定义水印id
    const id = '1.234567890.123456'
    // 如果document中存在该id的水印，则删除该水印
    if (document.getElementById(id) != null) {
      document.body.removeChild(document.getElementById(id) as HTMLElement)
    }
  }
}

export default watermark

// 使用示例
// watermark.set('水印内容')
// watermark.del()
// 注意：水印内容需要是字符串类型
// 注意：水印内容需要是字符串类型
